<template>
  <el-container>
    <el-header>
      <!-- <el-button type="primary" @click="onAddLayer">加载图层</el-button>
      <el-button type="primary" @click="clearLayer">清除图层</el-button> -->
      <Header />
      <!-- <el-button @click="onDraw">自定义</el-button> -->
    </el-header>
    <el-main>
      <div id="map"></div>
    </el-main>
  </el-container>

  <Menus v-if="mapStore.leftMenu.visible" />

  <el-dialog
    v-model="dialogVisible"
    title="摄像头信息"
    width="800"
    :before-close="handleClose"
  >
    <span>This is a message</span>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="Date" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
    </el-table>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">
          关闭
        </el-button>
      </div>
    </template> -->
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet.pm";
import "leaflet.pm/dist/leaflet.pm.css";
import pinia from "@/store/pinia.js";
import { useStore } from "@/store/index.js";
import Header from "@/components/header/index.vue";
import Menus from "@/components/left-menus/index.vue";
import camera from "@/assets/camera3.png";
import nav from "@/assets/nav.png";
import csxData from "@/assets/csx.json";
import csxNetData from "@/assets/csx-net.json";
const mapStore = useStore(pinia);

let map = ref(null);
const dialogVisible = ref(false);

const clearLayer = () => {
  // 清除所有的图层
  const allLayers = map.value._layers; // 注意：_layers是一个内部属性，可能在未来版本中改变

  // 遍历所有图层，并检查它们是否是L.layerGroup的实例
  for (const layerId in allLayers) {
    const layer = allLayers[layerId];

    // 检查图层是否是L.layerGroup的实例
    if (layer instanceof L.LayerGroup) {
      // 如果是，则从地图上移除它
      map.value.removeLayer(layer);
    }

    // 注意：对于嵌套的layerGroup（即layerGroup中包含其他layerGroup），
    // 你可能需要递归地处理它们，但上面的代码只处理了一级layerGroup。
  }
};

const handleClose = (done) => {
  dialogVisible.value = false;
};

const tableData = [
  {
    date: "2016-05-03",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles",
  },
  {
    date: "2016-05-02",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles",
  },
  {
    date: "2016-05-04",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles",
  },
  {
    date: "2016-05-01",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles",
  },
];

const onAddLayer = () => {
  clearLayer();

  const layerGroups = L.layerGroup().addTo(map.value);

  console.log("轮廓点个数：");
  console.log(csxData.features[0]["geometry"]["coordinates"][0][0].length);

  for (
    let i = 0;
    i < csxData.features[0]["geometry"]["coordinates"][0][0].length;
    i++
  ) {
    if (i % 20 !== 0) {
      continue;
    }
    const point = csxData.features[0]["geometry"]["coordinates"][0][0][i];
    const marker = L.marker([point[1], point[0]], {
      icon: L.divIcon({
        html: `<img src="${camera}" alt="Marker" style="transform: rotate(${
          i * 5
        }deg);">`,
        iconSize: [16, 16],
        className: "my-div-icon",
      }),
      title: "test",
      draggable: true,
    })
      .addTo(layerGroups)
      .bindPopup(
        "<h2>监控照片</h3><div><a href='http://www.baidu.com' target='_blank'><img width='500' src='https://img0.baidu.com/it/u=3620159376,1528769435&fm=253&fmt=auto&app=138&f=JPEG?w=640&h=480'/></a></div>",
        { maxWidth: "500px", direction: "top", offset: [0, 0] }
      )
      .on("click", function () {
        marker.openPopup();
      });

    marker.data = {
      index: i,
    };

    marker.on("click", function (e) {
      console.log(e.target.data);
      dialogVisible.value = true;
    });
  }
};

const onDraw = () => {
  map.value.pm.enableDraw("Polygon", {
    snappable: true,
    snapDistance: 20,
  });
};

onMounted(() => {
  map.value = L.map("map", {zoomControl: false}).setView([28.251818487944, 113.08755916596], 10);

  L.tileLayer("http://localhost:3000/{z}/{x}/{y}/tile.png", {
    minZoom: 10,
    maxZoom: 14,
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  }).addTo(map.value);

  L.geoJSON(csxData, {
    style: {
      weight: 5,
      opacity: 1,
      color: "#0080FF", //边界颜色
      fillOpacity: 0,
      fillColor: "#0080FF", //填充颜色 默认透明度为0.2
    },
  }).addTo(map.value);

  L.geoJSON(csxNetData, {
    style: {
      weight: 2,
      opacity: 1,
      color: "#FF0000", //边界颜色
      fillOpacity: 0,
      fillColor: "#0080FF", //填充颜色 默认透明度为0.2
    },
  }).addTo(map.value);

  // leaflet.pm begin 参考：https://www.jb51.net/javascript/325702oz2.htm
  map.value.pm.addControls({
    position: "topright",
    drawPolygon: true, // 绘制多边形
    drawMarker: true, //绘制标记点
    drawCircleMarker: false, //绘制圆形标记
    drawPolyline: true, //绘制线条
    drawRectangle: true, //绘制矩形
    drawCircle: true, //绘制圆圈
    editMode: true, //编辑多边形
    dragMode: true, //拖动多边形
    cutPolygon: true, // 添加一个按钮以删除多边形里面的部分内容
    removalMode: true, // 清除多边形
  });

  map.value.pm.setLang('zh');

  map.value.on("pm:create", (e) => {
    console.log(e, "绘制完成时调用");
    if (e.shape == "Circle") {
      console.log(e.layer._latlng, e.layer._radius, "绘制坐标");
    } else {
      console.log(e.layer._latlngs[0], "绘制坐标");
    }
  });

  // leaflet.pm end

  // leaflet.draw begin
});
</script>

<style scoped>
.el-header {
  width: 100%;
  height: 100px;
  padding: 0 15px 0 15px;
  background: #06f;
  box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.2);
}

.el-main {
  height: calc(100vh - 100px);
  padding: 0;
}

#map {
  height: 100%;
}
</style>